package com.fly.core.utils;

import java.io.IOException;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * JsonBean转换工具
 * 
 * @author 00fly
 *
 */
public class JsonBeanUtils
{
    private static ObjectMapper objectMapper = new ObjectMapper();
    
    /**
     * bean转json字符串
     * 
     * @param bean
     * @return
     * @throws IOException
     */
    public static String beanToJson(Object bean)
        throws IOException
    {
        return beanToJson(bean, false);
    }
    
    /**
     * bean转json字符串
     * 
     * @param bean
     * @param pretty 是否格式美化
     * @return
     * @throws IOException
     */
    public static String beanToJson(Object bean, boolean pretty)
        throws IOException
    {
        String jsonText = objectMapper.writeValueAsString(bean);
        JsonNode jsonNode = objectMapper.readTree(jsonText);
        return pretty ? jsonNode.toPrettyString() : jsonNode.toString();
    }
    
    /**
     * json字符串转bean
     * 
     * @param jsonText
     * @return
     * @throws IOException
     */
    public static <T> T jsonToBean(String jsonText, Class<T> clazz)
        throws IOException
    {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        return objectMapper.readValue(jsonText, clazz);
    }
    
    /**
     * json字符串转bean
     * 
     * @param jsonText
     * @param clazz
     * @param ingoreError 是否忽略无法识别字段
     * @return
     * @throws IOException
     */
    public static <T> T jsonToBean(String jsonText, Class<T> clazz, boolean ingoreError)
        throws IOException
    {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, !ingoreError);
        return objectMapper.readValue(jsonText, clazz);
    }
    
    /**
     * json字符串转bean
     * 
     * @param jsonText
     * @return
     * @throws IOException
     */
    public static <T> T jsonToBean(String jsonText, JavaType javaType)
        throws IOException
    {
        return objectMapper.readValue(jsonText, javaType);
    }
    
    /**
     * json字符串转bean
     * 
     * @param jsonText
     * @return
     * @throws IOException
     */
    public static <T> T jsonToBean(String jsonText, TypeReference<T> typeRef)
        throws IOException
    {
        return objectMapper.readValue(jsonText, typeRef);
    }
}
